package com.b2c.erp.controller.shop;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.b2c.erp.controller.CommonControllerUtils;
import com.b2c.interfaces.WmsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.api.ApiResult;
import com.b2c.entity.DataRow;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.erp.vo.ShopGoodsSkuLinkErpSkuVo;
import com.b2c.entity.pdd.ShopGoodsEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.pdd.ShopGoodsService;

@Controller
@RequestMapping("/shop")
public class ShopGoodsController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopGoodsService goodsService;
    @Autowired
    private ErpGoodsService erpGoodsService;
    @Autowired
    private WmsUserService manageUserService;
    private static Logger log = LoggerFactory.getLogger(ShopGoodsController.class);

    @RequestMapping(value = "/goods_list", method = RequestMethod.GET)
    public String getList(Model model, HttpServletRequest request) {
        Integer shopType = null;

        if(StringUtils.hasText(request.getParameter("shopType"))){
            try {
                shopType = Integer.parseInt(request.getParameter("shopType"));
                model.addAttribute("shopType", shopType);
            } catch (Exception e) {
            }
        }
        //店铺列表
        List<DcShopEntity> shops = shopService.getShopList(shopType);
        model.addAttribute("shops", shops);
        

        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        String goodsNum = null;
        if (!StringUtils.isEmpty(request.getParameter("goodsNum"))) {
            goodsNum = request.getParameter("goodsNum");
            model.addAttribute("goodsNum", goodsNum);
        }
        Integer shopId = null;
        if (!StringUtils.isEmpty(request.getParameter("shopId"))) {
            shopId = Integer.parseInt(request.getParameter("shopId"));
            model.addAttribute("shopId", shopId);
        }
        Integer isOnsale = 1;
        if (!StringUtils.isEmpty(request.getParameter("isOnsale"))) {
            isOnsale = Integer.parseInt(request.getParameter("isOnsale"));
        }
        model.addAttribute("isOnsale", isOnsale);

        var result = goodsService.getGoodsList(shopType,shopId,pageIndex,pageSize,goodsNum,null,isOnsale);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

       if(shopType!=null && shopType==5){
//        model.addAttribute("view", "pddgoods");
//        model.addAttribute("pView", "pdd");
           CommonControllerUtils.setViewKey(model, manageUserService, "pddshop");
       }else if(shopType!=null && shopType==4){
//        model.addAttribute("view", "taogoods");
//        model.addAttribute("pView", "tao");
           CommonControllerUtils.setViewKey(model, manageUserService, "taoshop");
       }else  if(shopType!=null && shopType==6){
//        model.addAttribute("view", "dougoods");
//        model.addAttribute("pView", "dou");
           CommonControllerUtils.setViewKey(model, manageUserService, "dyshop");
       }
       else{
           CommonControllerUtils.setViewKey(model, manageUserService, "shopGoods");
       }
        return "eshop/shop_goods_list";
    }

    @RequestMapping(value = "/link_erp_goods_spec", method = RequestMethod.GET)
    public String LinkErpGoodsSpec(Model model,@RequestParam Long goodsId, HttpServletRequest request) {
        var goods = goodsService.getGoodsById(goodsId);
        model.addAttribute("goodsId", goodsId);
        if(StringUtils.hasText(goods.getGoodsNum())){
            //数据库里有商品编码，查询sku List
            var skuList = goodsService.getGoodsSkuListByGoodsId(goodsId);
            model.addAttribute("lists", skuList); 

            var erpSkuList = erpGoodsService.getSpecByGoodsNumber(1, 500, goods.getGoodsNum());
            // model.addAttribute("erpSkuList", erpSkuList.getList()); 
            List<ShopGoodsLinkErpSkuVo> vos = new ArrayList<>();
            for (var it : erpSkuList.getList()) {
                ShopGoodsLinkErpSkuVo vo = new ShopGoodsLinkErpSkuVo();
                vo.setId(it.getId());
                String spec = "";
                if(StringUtils.hasText(it.getColorValue())){
                    spec+= it.getColorValue();
                }
                if(StringUtils.hasText(it.getStyleValue())){
                    spec+= it.getStyleValue();
                }
                if(StringUtils.hasText(it.getSizeValue())){
                    spec+= it.getSizeValue();
                }

                vo.setSpec(spec);
                vo.setNum(it.getSpecNumber());
                vos.add(vo);
            }
            model.addAttribute("erpSkuList", vos); 
            model.addAttribute("erpSkuListJSON", JSONObject.toJSONString(vos)); 
            
        }




        
        
        return "eshop/shop_goods_link_erp_goods_sku";
    }

    @ResponseBody
    @RequestMapping(value = "/link_erp_goods_spec_all_ajax", method = RequestMethod.POST)
    public ApiResult<Integer> link_erp_goods_spec_all_ajax(HttpServletRequest req, @RequestBody DataRow reqData){
        Long goodsId = reqData.getLong("goodsId");
        String skuCode = reqData.getString("skuCode");
        
        if(goodsId==null || goodsId <= 0 )
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "GoodsId不能为空");
        if(StringUtils.hasText(skuCode)==false )
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "请关联SKU");
        String[] skus = skuCode.split(",");
        List<ShopGoodsSkuLinkErpSkuVo> skuLinkList = new ArrayList<>();
        
        for (var s : skus) {
            if(StringUtils.hasText(s)){
                String[] ss= s.split("-");
                if(ss.length==2){
                    ShopGoodsSkuLinkErpSkuVo v = new ShopGoodsSkuLinkErpSkuVo();
                    v.setErpSkuId(Integer.parseInt(ss[1]));
                    v.setShopGoodsSkuId(Long.parseLong(ss[0]));
                    skuLinkList.add(v);
                }
            }
        }
        var res = goodsService.linkErpSkuAll(goodsId,skuLinkList);
     
        log.info(res.getMsg());
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), res.getMsg());
    }

    /**
     * 修改商品编码
     * @param req
     * @param reqData
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/up_goodsNum_ajax", method = RequestMethod.POST)
    public ApiResult<Integer> upGoodsNumAjax(HttpServletRequest req, @RequestBody DataRow reqData){
        Long goodsId = reqData.getLong("id");
        String goodsNum = reqData.getString("goodsNum");
        if(goodsId==null || goodsId <= 0 )
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "id不能为空");
        if(StringUtils.hasText(goodsNum) == false)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "请输入商品编码");
        log.info("修改商品编码，id:"+goodsId+",goodsNum:"+goodsNum);

        var res = goodsService.upGoodsNumById(goodsId,goodsNum);
        if(res.getCode()  == EnumResultVo.SUCCESS.getIndex())
            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS",res.getData());
        else
            return new ApiResult<>(EnumResultVo.Fail.getIndex(), res.getMsg());
    }
    /**
     * 关联erp系统商品规格
     * @param req
     * @param reqData
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/link_erp_goods_spec_ajax", method = RequestMethod.POST)
    public ApiResult<Integer> getOrderList(HttpServletRequest req, @RequestBody DataRow reqData){
        Long xhsGoodsSpecId = reqData.getLong("id");
        String erpCode = reqData.getString("code");
        if(xhsGoodsSpecId==null || xhsGoodsSpecId <= 0 )
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "id不能为空");
        if(StringUtils.hasText(erpCode) == false)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "请输入SKU编码");
        log.info("ID:"+xhsGoodsSpecId+",Code:"+erpCode);

        var res = goodsService.linkErpGoodsSpec(xhsGoodsSpecId,erpCode);
        if(res.getCode()  == EnumResultVo.SUCCESS.getIndex())
            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS",res.getData());
        else
            return new ApiResult<>(EnumResultVo.Fail.getIndex(), res.getMsg());
    }


    @RequestMapping(value = "/goods_add", method = RequestMethod.GET)
    public String add(Model model, HttpServletRequest request) {
        //店铺列表
        List<DcShopEntity> shops = shopService.getShopList(null);
        model.addAttribute("shops", shops);


        return "eshop/shop_goods_add";
    }

    @ResponseBody
    @RequestMapping(value = "/goods_add_ajax", method = RequestMethod.POST)
    public  ApiResult<String> addPostAjax(Model model, @RequestBody DataRow data, HttpServletRequest request) {
        String title = data.getString("title");
        Integer shopId = data.getInt("shopId");
        var shop =  shopService.getShop(shopId);
        Long goodsId = data.getLong("goodsId");
        String goodsNum = data.getString("goodsNum");
        String goodsImg = data.getString("goodsImg");
        Double price = data.getDouble("price");
        String publishDate = data.getString("publishDate");
        
        ShopGoodsEntity goods = new ShopGoodsEntity();
        goods.setGoodsId(goodsId);
        goods.setThumbUrl(goodsImg);
        goods.setShopId(shopId);
        goods.setShopType(shop.getType());
        goods.setGoodsName(title);
        goods.setGoodsNum(goodsNum);
        goods.setPrice(new BigDecimal(price));
        goods.setPublishTime(publishDate);
        goods.setIsOnsale(1);
        var result = goodsService.addGoods(goods);
        
        return new ApiResult<>(result.getCode(), result.getMsg());
    }

    @ResponseBody
    @RequestMapping(value = "/up_publish_time_ajax", method = RequestMethod.POST)
    public  ApiResult<String> upPublishTime(Model model, @RequestBody DataRow data, HttpServletRequest request) {
       
        Long goodsId = data.getLong("id");
        String publishTime = data.getString("publishTime");
       
        var result = goodsService.updatePublishTime(goodsId,publishTime);
        
        return new ApiResult<>(result.getCode(), result.getMsg());
    }

    
    @ResponseBody
    @RequestMapping(value = "/up_goods_remark_ajax", method = RequestMethod.POST)
    public  ApiResult<String> goodsRemarkEdit(Model model, @RequestBody DataRow data, HttpServletRequest request) {
       
        Long goodsId = data.getLong("id");
        String remark = data.getString("remark");
       
        var result = goodsService.updateRemark(goodsId,remark);
        
        return new ApiResult<>(result.getCode(), result.getMsg());
    }

    @ResponseBody
    @RequestMapping(value = "/up_isOnsale_ajax", method = RequestMethod.POST)
    public  ApiResult<String> upIsOnsale(Model model, @RequestBody DataRow data, HttpServletRequest request) {
       
        Long goodsId = data.getLong("id");
       
       
        var result = goodsService.updateIsOnsale(goodsId);
        
        return new ApiResult<>(result.getCode(), result.getMsg());
    }
    @ResponseBody
    @RequestMapping(value = "/up_totalSales_ajax", method = RequestMethod.POST)
    public  ApiResult<String> up_totalSales_ajax(Model model, @RequestBody DataRow data, HttpServletRequest request) {
       
        Long goodsId = data.getLong("id");
        Integer totalSales = data.getInt("totalSales");
       
       
        var result = goodsService.updateTotalSales(goodsId,totalSales);
        
        return new ApiResult<>(result.getCode(), result.getMsg());
    }
    
}
